<template>
  <div class="tab-container">
    <ul class="tabs">
      <li
        v-for="(item, index) in info"
        :class="{ active: index === tabIndex }"
        :key="index" @click="toSelectTabItemHandler(item, index)"
      >
      {{ tabKey ? item[tabKey] : item }}
      </li>
    </ul>
    <div class="line" :style="{ width: `${tabWidth}px`, transform: `translateX(${tabLeft}px)` }"></div>
  </div>
</template>

<script>
export default {
  props: {
    info: {
      type: Array,
      default: () => []
    },
    tabKey: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      tabIndex: 0,
      tabWidth: 0,
      tabLeft: 0
    }
  },

  mounted () {
    this.setTabActive()
  },

  methods: {
    /**
     * 点击选中tab
     * @param { Object } tab   当前点击的tab
     * @param { Number } index 当前点击的索引
     */
    toSelectTabItemHandler (tab, index) {
      // 向父级触发时间
      this.$emit('onTab', tab)
      // 记录当前索引
      this.tabIndex = index
      // 设置tab索引状态
      this.setTabActive(index)
    },

    /**
     * 设置tab是激活状态
     */
    setTabActive () {
      // 距离左边的距离
      let left = 0
      // 取出左边的距离
      for (let index = 0; index < this.tabIndex; index++) {
        left += this.getTabStyle(index)
      }
      // 设置长度
      this.tabWidth = this.getTabStyle(this.tabIndex) - 60
      // 设置左边距离
      this.tabLeft = left + 30
    },

    /**
     * 获取激活的tab项的宽和高
     * @param { Number } index 当前tab索引
     */
    getTabStyle (index = 0) {
      // 获取dom元素
      const tab = document.querySelector(`.tabs li:nth-child(${index + 1})`)
      // tab的长
      let width = 0
      // 如果获取了元素
      if (tab) {
        width = tab.offsetWidth
      }
      return width
    }
  }
}
</script>

<style lang="less" scoped>
@import "../styles/variable.less";

.tab-container {
  position: relative;
  .tabs {
    font-size: 16px;
    font-weight: bold;
    overflow: hidden;
    li {
      cursor: pointer;
      float: left;
      padding: 6px 30px;
      transition: color 0.3s ease;
      &.active {
        color: @font-color-golden;
      }
      &:hover {
        color: @font-color-golden;
      }
    }
  }
  .line {
    background-color: @font-color-golden;
    height: 2px;
    transition: transform 300ms ease;
  }
}
</style>
